﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace IQReportes.Utils
{
    /// <summary>
    /// Clase para descarga de archivo excel
    /// </summary>
    public class DownloadFileActionResult : ActionResult
    {
        /// <summary>
        /// datos de excel
        /// </summary>
        public string ExcelGridView { get; set; }
        /// <summary>
        /// nombre de archivo excel
        /// </summary>
        public string fileName { get; set; }

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="gv">datos</param>
        /// <param name="pFileName">nombre de archivo excel</param>
        public DownloadFileActionResult(string gv, string pFileName)
        {
            ExcelGridView = gv;
            fileName = pFileName;

        }

        /// <summary>
        /// generar archivo excel
        /// </summary>
        /// <param name="context">contexto  </param>
        public override void ExecuteResult(ControllerContext context)
        {

            //Create a response stream to create and write the Excel file
            HttpContext curContext = HttpContext.Current;
            curContext.Response.Clear();
            curContext.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
            curContext.Response.Charset = "";
            curContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            curContext.Response.ContentType = "application/ms-excel";

            //Open a memory stream that you can use to write back to the response
            byte[] byteArray = Encoding.ASCII.GetBytes(ExcelGridView);
            MemoryStream s = new MemoryStream(byteArray);
            StreamReader sr = new StreamReader(s, Encoding.Unicode);

            //Write the stream back to the response
            curContext.Response.ContentEncoding = System.Text.Encoding.Unicode;
            curContext.Response.Write(sr.ReadToEnd());
            curContext.Response.End();
        }
    }
}